﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using log4net;

namespace CourseSystem.Common.Helpers
{
    public class AttachmentsHelper
    {
        private static readonly Regex AttachReg = new Regex("(?<=" + CommonHelper.Domain + ")[^\"]*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly ILog Log = LogManager.GetLogger(typeof(AttachmentsHelper));

        /// <summary>
        /// 清理没有使用的附件,并更新已使用附件的id及随机串置空
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ranStr"></param>
        /// <param name="contentId"></param>
        public static void ClearUselessAttach(string content, string ranStr, int contentId)
        {
            if (string.IsNullOrEmpty(ranStr))
            {
                Log.Error("清理没有使用的附件遇到Null随机字符串,可能是Session超时导致.");
                return;
            }
            if (contentId == 0)
            {
                Log.Error("contentId:" + contentId);
                return;
            }
            var existList = AttachmentsBLL.GetByExpress(o => o.RanSign == ranStr || o.ContentId == contentId);
            var toDelList = new List<AttachmentsInfo>();
            if (AttachReg.IsMatch(content))
            {
                var cols = AttachReg.Matches(content);
                var list = (from object item in cols select item.ToString()).ToList();
                var toUpdate = new List<AttachmentsInfo>();
                foreach (var item in existList)
                {
                    if (list.Contains(item.FileName))
                    {
                        item.ContentId = contentId;
                        item.RanSign = "";
                        toUpdate.Add(item);
                    }
                    else
                        toDelList.Add(item);
                }
                AttachmentsBLL.Edit(toUpdate);
            }
            else
                toDelList = existList;
            AttachmentsBLL.DelFileByList(toDelList);
        }

        public static void ClearUselessAttach()
        {
            AttachmentsBLL.DelFileByExpress(
                o => o.ContentId == 0 && o.PostDate.AddDays(2) < DateTime.Now);
        }
    }
}
